//
//  ChatViewController.m
//  QQ界面
//
//  Created by apple on 16/10/27.
//  Copyright © 2016年 LWB. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatCell.h"
#import "ChatModelFrame.h"
#import "ChatModel.h"
@interface ChatViewController ()<UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate>
//使用一个可变数组来保存所有的frame模型对象
@property(nonatomic, strong)NSMutableArray * messageFrames;
//tableView
@property(nonatomic, strong)UITableView * tbView;
@property(nonatomic ,strong)NSMutableArray *allmessageFrames;
//输入栏的uiview
@property(nonatomic, strong)UIView * inputView;
//1.语言键
@property(nonatomic, strong)UIButton * soundBtn;
//2.输入框
@property(nonatomic, strong)UITextField * inputFd;
//3.表情键
@property(nonatomic, strong)UIButton * faceBtn;
//4.加号键
@property(nonatomic, strong)UIButton * plusBtn;

//
@property(nonatomic, strong)NSMutableArray * arrayDict;

@end

@implementation ChatViewController
#pragma mark -懒加载
-(NSMutableArray *)allmessageFrames{
    //如果已经有了这份数据，那就不在加载新的，只有该数据不存在的时候才加载
    if (_allmessageFrames == nil) {
        //加载模型数据
        //1.将plist文件中的数据保存到一个新的字典数组中
        //1.1拿到plist文件的路径
        NSString * path = [[NSBundle mainBundle]pathForResource:@"chatmessages.plist" ofType:nil];
        //1.2将plist文件中的所有字典保存到一个数组中。
        NSArray * arrayDict = [NSArray arrayWithContentsOfFile:path];
        _arrayDict = [[NSMutableArray alloc]initWithArray:arrayDict];
        //2.创建一个可变数组来接收所有的模型对象
        NSMutableArray * arrayModels = [NSMutableArray array];
        //3.转化模型字典
        for (NSArray *arr1  in arrayDict) {
             NSMutableArray *arrModels1 = [[NSMutableArray alloc]init];
            for (NSArray *arr2 in arr1) {
                NSMutableArray *arrModels2 = [[NSMutableArray alloc]init];
                for (NSDictionary* dict in arr2) {
                    //3.1 创建一个消息模型对象
                    ChatModel * model = [ChatModel ChatModelWithDict:dict];
                    //3.2 创建一个frame模型
                    ChatModelFrame * modelFrame = [[ChatModelFrame alloc]init];
                    modelFrame.chatModel = model;
                    //3.3 将frame模型对象添加到数组
                    [arrModels2 addObject:modelFrame];
                }
                [arrModels1 addObject:arrModels2];
            }
            [arrayModels addObject:arrModels1];
        }
        _allmessageFrames = arrayModels;
    }
    return _allmessageFrames;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//      [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Action:) name:@"chat" object:nil];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //设置模型数据
    [self allmessageFrames];
    [self getPersonalMessage];
    //NSLog(@"models:%@", _messages);
    //设置导航栏
    [self navSet];
   // self.hidesBottomBarWhenPushed = NO;
    //设置tableView
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect tbFrame = CGRectMake(0,self.navigationController.navigationBar.frame.size.height+20, screenSize.width, screenSize.height-self.navigationController.navigationBar.frame.size.height-[[UIApplication sharedApplication]statusBarFrame].size.height-50);
    _tbView = [[UITableView alloc]initWithFrame:tbFrame style:UITableViewStylePlain];
    _tbView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1221"]];
    _tbView.sectionFooterHeight = 0;
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tbView.dataSource = self;
    _tbView.delegate = self;
    //设置tableview的背景色
   // _tbView.backgroundColor = [UIColor  colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:0.8];
    //取消分割线
    _tbView.separatorStyle = NO;
    [self.view addSubview:_tbView];
    //添加聊天输入栏
    [self addInput];
    
    //处理键盘的弹出事件，避免键盘弹出覆盖消息输入栏
    //1.发布者：系统
    //2.监听者：self
    //3.通知中心：center
  //  NSNotificationCenter * center = [NSNotificationCenter defaultCenter];

    //设置文本输入框的代理
    self.inputFd.delegate = self;
}
-(instancetype)init{
    if (self = [super init]) {
        NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
        //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
        [center addObserver:self selector:@selector(notice:) name:@"123" object:nil];
        [center addObserver:self selector:@selector(keyboardUp:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}
-(void)notice:(id)ser{
    NSLog(@"%@",ser);
}
-(void)Action:(NSNotification *)not{
    _row=(NSInteger)not.userInfo[@"row"];
    _section =(NSInteger)not.userInfo[@"section"];
    NSLog(@"%@",not.userInfo);
}
//实现通知的方法
-(void)keyboardUp:(NSNotification*)notoInfo
{
    //1.获取键盘的最大y值
    CGRect rectEnd = [notoInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = rectEnd.origin.y;
    //2.计算聊天界面要往上平移的高度
    CGFloat upValue = keyboardY - self.view.bounds.size.height;
    //3.实现键盘弹出时的平移动画效果
    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, upValue);
    }];
}


//实现添加聊天信息输入栏
-(void)addInput
{
    //初始化inputView
    //CGFloat separate = [UIScreen mainScreen].bounds.size.width/7;
  //  NSLog(@"%f",separate);
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0,self.view.bounds.size.height-50, _tbView.bounds.size.width, 50)];
  //  _inputView.backgroundColor = [UIColor redColor];
    //_inputView.backgroundColor = [UIColor greenColor];
    
    //添加控件
    //1.语言键
    _soundBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 5,40,40)];
    [self setBtnBackImage:_soundBtn andImgName:@"chat_bottom_voice_nor" andImgName2:@"chat_bottom_voice_press"];
    [_inputView addSubview:_soundBtn];
    //2.输入框
    _inputFd = [[UITextField alloc]initWithFrame:CGRectMake(40, 8, _tbView.bounds.size.width-3*40,35)];
    [_inputFd setBackground:[UIImage imageNamed:@"chat_bottom_textfield"]];
    //在左边添加一个空白UIView，让光标右移一点点
    UIView * leftVw = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 40)];
    _inputFd.leftView = leftVw;
    _inputFd.leftViewMode = UITextFieldViewModeAlways;
    [_inputView addSubview:_inputFd];
    //3.表情键
    _faceBtn = [[UIButton alloc]initWithFrame:CGRectMake(_tbView.bounds.size.width- 40*2, 5,40,40)];
    [self setBtnBackImage:_faceBtn andImgName:@"chat_bottom_smile_nor" andImgName2:@"chat_bottom_smile_press"];
    [_inputView addSubview:_faceBtn];
    //4.加号键
    _plusBtn = [[UIButton alloc]initWithFrame:CGRectMake(_tbView.bounds.size.width- 40, 5,  40,40)];
    [self setBtnBackImage:_plusBtn andImgName:@"chat_bottom_up_nor" andImgName2:@"chat_bottom_up_press"];
    [_inputView addSubview:_plusBtn];
    
    [self.view addSubview:_inputView];
    
}

//封装设置按钮背景图的方法
-(void)setBtnBackImage:(UIButton *)btn andImgName:(NSString*)imgName andImgName2:(NSString*)imgName2
{
    //设置按钮背景图
    [btn setBackgroundImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:imgName2] forState:UIControlStateHighlighted];
}

#pragma mark - 文本输入框代理方法
//获取文本框内容(文本输入框的代理)
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //发送按钮被点击，输入框代理方法
    //1.获取文本框内容
    NSString * text = textField.text;
    //2.我发送该内容
    [self sendMessage:MessageTypeMe withText:text];
    //3.模拟别人回复消息
    [self sendMessage:MessageTypeOther withText:@"我现在很忙，待会再理你"];
    //4.清空输入框
    textField.text = nil;
    textField.returnKeyType = UIReturnKeySend;
    return YES;
}

//发送消息的封装方法
-(void)sendMessage:(MessageType)type withText:(NSString*)text
{
    //1.创建数据模型对象
     ChatModel* model = [[ChatModel alloc]init];
    //设置数据模型的数据
    //1.1 正文
    model.text = text;
    //1.2 发送时间，当前时间
    NSDate * nowDate = [NSDate date];
    //转成： （今天 HH:mm）
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"今天 HH:mm";
    model.time = [formatter stringFromDate:nowDate];
    //1.3 类别
    model.type = type;
    
    
    /*******/
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * plistPath1 = [paths objectAtIndex:0];
    NSString * path = [plistPath1 stringByAppendingPathComponent:@"messages.plist"];
    [_arrayDict addObject:model];
    [_arrayDict writeToFile:path atomically: YES];
    //2. 创建frame模型对象
    ChatModelFrame * modelFrame = [[ChatModelFrame alloc]init];
    //3. 将数据模型对象添加到frame模型对象
    modelFrame.chatModel = model;
    //4. 将新的frame模型对象添加到frame模型数组中
    [_messageFrames addObject:modelFrame];
    //5. 刷新tableview
    [_tbView reloadData];
    //6. 将最新的消息显示在最后一行
    //获取发送消息后的tableview的indexpath
    NSIndexPath * lastIndexPath = [NSIndexPath indexPathForRow:_messageFrames.count-1 inSection:0];
    //将最后一行平移上来
    [_tbView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}



#pragma mark - 数据源方法
//当tableview滚动的时候回收键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
//返回多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _messageFrames.count;
}
-(void )getPersonalMessage{
   NSLog(@"22%ld",(long)_section);
    NSArray *section1 = _allmessageFrames[_section];
    _messageFrames =section1[_row];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr =_messageFrames;
    //1.获取模型
    ChatModelFrame * modelFrame = arr[indexPath.row];
    //2.创建cell
    //可重用id创建cell，保证cell只有一个，不会被反复创建，降低内存消耗
    static NSString * ID = @"message_cell";
    ChatCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    //判断cell是否为空，为空说明程序还没有cell
    if (cell == nil) {
        cell = [[ChatCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    //把frame模型设置给cell
    cell.backgroundColor = [UIColor clearColor];
    cell.chatModelFrame = modelFrame;
    //cell不能被点击
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
//返回行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatModelFrame * messageFrame = self.messageFrames[indexPath.row];
    return messageFrame.rowHeight;
}

#pragma mark - 其它方法
//导航栏数据设置
-(void)navSet
{
    //导航栏的item
    UIBarButtonItem * baritem = [[UIBarButtonItem alloc]initWithTitle:@"消息(12)" style:UIBarButtonItemStylePlain target:self action:@selector(message)];
    self.navigationItem.leftBarButtonItem = baritem ;
}

-(void)message
{
    //LLQTwoViewController * two = [[LLQTwoViewController alloc] init];
    //[self.navigationController pushViewController:two animated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
    //[self popoverPresentationController];
}
-(void)dealloc{
  //  [self dealloc];
        //注册为观察者的对象,需要在被系统dealloc之前,取消掉自己的观察者身份
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
